package com.gjs.sso.config.security.sms;

import com.gjs.common.manager.SmsVerifyCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
public class SmsVerifyCodeFilter extends UsernamePasswordAuthenticationFilter {

    private SmsVerifyCode smsVerifyCode;

    public SmsVerifyCodeFilter(SmsVerifyCode smsVerifyCode) {
        //匹配的目标请求
        super.setRequiresAuthenticationRequestMatcher(new AntPathRequestMatcher("/mobile_login", "POST"));
        this.smsVerifyCode = smsVerifyCode;
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        String mobile = request.getParameter("mobile");
        String smsVerificationCode = request.getParameter("smsVerificationCode");

        // 校验验证码
        if (!smsVerifyCode.verify(SmsVerifyCode.VerifyType.LOGIN, mobile, smsVerificationCode)) {
            throw new BadCredentialsException("短信验证码错误");
        }

        // 实例化SmsVerifyCodeAuthenticationToken
        SmsVerifyCodeAuthenticationToken authRequest = new SmsVerifyCodeAuthenticationToken(mobile);
        // 将请求的信息设置到token中
        authRequest.setDetails(authenticationDetailsSource.buildDetails(request));
        // 调用AuthenticationManager进行验证
        return this.getAuthenticationManager().authenticate(authRequest);
    }
}
